package com.ccteam.fluidmusic.ui.user

import androidx.lifecycle.*
import com.ccteam.fluidmusic.utils.cancelIfActive
import com.ccteam.fluidmusic.view.bean.ErrorMessage
import com.ccteam.fluidmusic.view.bean.LoadMessage
import com.ccteam.model.Resource
import com.ccteam.shared.core.UserCore
import com.ccteam.shared.domain.user.MeHomeDataUseCase
import com.ccteam.shared.result.BaseItemData
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/19
 *
 * 我的界面相关ViewModel
 */
@HiltViewModel
class MeViewModel @Inject constructor(
    private val meHomeDataUseCase: MeHomeDataUseCase,
    userCore: UserCore
): ViewModel() {

    private val meHomeListResult = MutableLiveData<Resource<List<BaseItemData>>>()

    private val _meHomeList = MutableLiveData<List<BaseItemData>>()
    val meHomeList: LiveData<List<BaseItemData>> get() = _meHomeList

    val loadMessage: LiveData<LoadMessage> = meHomeListResult.map {
        when (it) {
            is Resource.Success -> {
                if(it.data.isNullOrEmpty()){
                    LoadMessage.Empty
                } else {
                    LoadMessage.NotLoading
                }
            }
            is Resource.Loading -> {
                LoadMessage.Loading
            }
            else -> {
                LoadMessage.Error(ErrorMessage(it.message,it.errorCode))
            }
        }
    }

    private var meJob: Job? = null
    init {
        meJob = viewModelScope.launch {
            userCore.isLogin.collectLatest {
                refreshUserInfo()
            }
        }
    }

    suspend fun refreshUserInfo(){
        meHomeDataUseCase(null).collectLatest {
            meHomeListResult.value = it

            _meHomeList.value = it.data ?: emptyList()

        }
    }

    override fun onCleared() {
        super.onCleared()
        meJob.cancelIfActive()
    }
}